<template>
  <el-dialog :visible.sync="dialog" title="分销佣金比例设置" width="80%" append-to-body>
    <div style="color: #ff0000; margin-bottom: 10px;">提示：直接输入数字，支持两位小数。如5.55%，输入5.55即可。</div>
    <div>
      <div style="margin-bottom: 10px;">提货点返佣比例配置</div>
      <div class="zy-box" v-loading="pickupDistributionSpinShow">
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold">比例</div>
          <p style="clear:both"></p>
        </div>
        <div class="zy-box-row" v-for="(item, index) in pickupDistributionRatioData" :key="index">
          <div class="zy-text-bold" style="width: 400px;">
            <p>{{item.roleTitle}} - {{item.roleDescription}}</p>
          </div>
          <el-input-number class="zy-input" placeholder="输入返佣比例" v-model="item.commissionPercent" />
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div style="margin-top: 15px;">
      <div style="margin-bottom: 10px;">顶级返佣比例配置</div>
      <div class="zy-box" v-loading="topDistributionSpinShow">
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold">比例</div>
          <p style="clear:both"></p>
        </div>
        <div class="zy-box-row" v-for="(item, index) in topDistributionRatioData" :key="index">
          <div class="zy-text-bold" style="width: 400px;">
            <p>{{item.roleTitle}} - {{item.roleDescription}}</p>
          </div>
          <el-input-number class="zy-input" placeholder="输入返佣比例" v-model="item.commissionPercent" />
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div style="margin-top: 15px;">
      <div style="margin-bottom: 10px;">
        分销返佣比例配置（一级分销商返佣比例
        <span style="font-weight: bold;">小于</span>二级分销商返佣比例）
      </div>
      <div class="zy-box" v-loading="distributionSpinShow">
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold" v-for="(item, index) in levelArr" :key="index">{{item}}级</div>
          <p style="clear:both"></p>
        </div>
        <div
          class="zy-box-row"
          v-for="(item, ratioIndex) in distributionRatioData"
          :key="ratioIndex"
        >
          <div class="zy-text-bold" style="width: 400px;">
            <p>{{item.roleTitle}} - {{item.roleDescription}}</p>
          </div>
          <div v-for="(levelItem, levelIndex) in levelArr" :key="levelIndex">
            <el-input-number
              class="zy-input"
              placeholder="输入返佣比例"
              v-model="item.commissionPercents[levelIndex]"
            />
          </div>
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button size="large" @click="dialog = false;">关闭</el-button>
      <el-button type="primary" @click="setDistributionRatio" :loading="setLoading">配置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as utils from '@/utils/utils'
import * as ResponseStatus from '@/utils/response-status'
export default {
  name: 'DistributionRatioDialog',
  props: {},
  components: {},
  data() {
    return {
      dialog: false,
      distributionSpinShow: false,
      topDistributionSpinShow: false,
      pickupDistributionSpinShow: false,
      setLoading: false,
      levelArr: [],
      distributionRatioData: [],
      topDistributionRatioData: [],
      pickupDistributionRatioData: [],
      goodsId: undefined,
      goodsTitle: undefined,
      goodsPicUrl: undefined,
      goodsIsActive: undefined,
      goodsSkuId: undefined,
      skuTitle: undefined,
      skuPicUrl: undefined,
      skuIsActive: undefined,
      type: null, //goods 或 goodsSku
      id: null, // goodsId 或 goodsSkuId
      topDistributionValidFlag: false,
      distributionValidFlag: false,
      pickupDistributionValidFlag: false,
    }
  },
  methods: {
    /**
     * 请求后台接口，获取数据
     */
    loadData(param, type, id) {
      if (param.goodsId) {
        this.goodsId = param.goodsId
      }
      if (param.goodsSkuId) {
        this.goodsSkuId = param.goodsSkuId
        this.skuTitle = param.skuTitle
        this.skuPicUrl = param.skuPicUrl
        this.skuIsActive = param.skuIsActive
      }
      this.goodsTitle = param.goodsTitle
      this.goodsPicUrl = param.goodsPicUrl
      this.goodsIsActive = param.goodsIsActive
      this.type = type
      this.id = id
      this.dialog = true
      this.topDistributionSpinShow = true
      this.distributionSpinShow = true
      this.pickupDistributionSpinShow = true
      // 先请求分销比例表
      utils
        .doPostJson('/goods-commission/admin/all-cond', param, {})
        .then((res) => {
          // 成功获取分销比例列表，继续获取角色
          let commissionList = res.data.rows
          this.loadPickupDistributionData(commissionList)
          this.loadTopDistributionData(commissionList)
          this.loadDistributionData(commissionList)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    loadPickupDistributionData(commissionList) {
      this.pickupDistributionRatioData = []
      utils
        .doGet('/role/admin/list-pickup-distribution-roles', {})
        .then((roleRes) => {
          let roleList = roleRes.data.rows
          let commissionLen = commissionList.length
          let roleLen = roleList.length
          for (let i = 0; i < roleLen; i++) {
            let roleItem = roleList[i]
            let ratioData = {
              roleId: roleItem.id,
              roleTitle: roleItem.title,
              roleDescription: roleItem.description,
              commissionPercent: undefined,
            }
            for (let j = 0; j < commissionLen; j++) {
              let commissionItem = commissionList[j]
              if (
                this.type === 'goods' &&
                roleItem.id === commissionItem.roleId &&
                !commissionItem.goodsSkuId
              ) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              } else if (
                this.type === 'goodsSku' &&
                roleItem.id === commissionItem.roleId &&
                commissionItem.goodsSkuId
              ) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              }
            }
            this.pickupDistributionRatioData.push(ratioData)
          }
          this.pickupDistributionSpinShow = false
        })
        .catch((roleErr) => {
          console.log(roleErr)
        })
    },
    loadTopDistributionData(commissionList) {
      this.topDistributionRatioData = []
      utils
        .doGet('/role/admin/list-top-distribution-roles', {})
        .then((roleRes) => {
          let roleList = roleRes.data.rows
          let commissionLen = commissionList.length
          let roleLen = roleList.length
          for (let i = 0; i < roleLen; i++) {
            let roleItem = roleList[i]
            let ratioData = {
              roleId: roleItem.id,
              roleTitle: roleItem.title,
              roleDescription: roleItem.description,
              commissionPercent: undefined,
            }
            for (let j = 0; j < commissionLen; j++) {
              let commissionItem = commissionList[j]
              if (
                this.type === 'goods' &&
                roleItem.id === commissionItem.roleId &&
                !commissionItem.goodsSkuId
              ) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              } else if (
                this.type === 'goodsSku' &&
                roleItem.id === commissionItem.roleId &&
                commissionItem.goodsSkuId
              ) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              }
            }
            this.topDistributionRatioData.push(ratioData)
          }
          this.topDistributionSpinShow = false
        })
        .catch((roleErr) => {
          console.log(roleErr)
        })
    },
    loadDistributionData(commissionList) {
      this.distributionRatioData = []
      utils
        .doGet('/role/admin/list-distribution-roles', {})
        .then((roleRes) => {
          // 成功获取角色列表，继续获取分销等级
          let roleList = roleRes.data.rows
          utils
            .doGet('/distribution/admin/distribution-level', {})
            .then((levelRes) => {
              // 成功获取分销等级，开始处理数据
              let level = levelRes.data - 1
              let levelArr = []
              for (let i = 0; i < level; i++) {
                levelArr.push(1 + i)
              }
              const commissionLen = commissionList.length
              const roleLen = roleList.length
              for (let i = 0; i < roleLen; i++) {
                let roleItem = roleList[i]
                let ratioData = {
                  roleId: roleItem.id,
                  roleTitle: roleItem.title,
                  roleDescription: roleItem.description,
                  commissionPercents: [],
                }
                for (let j = 0; j < commissionLen; j++) {
                  let commissionItem = commissionList[j]
                  if (
                    this.type === 'goods' &&
                    roleItem.id === commissionItem.roleId &&
                    !commissionItem.goodsSkuId
                  ) {
                    ratioData.commissionPercents.push(
                      commissionItem.commissionPercent
                    )
                  } else if (
                    this.type === 'goodsSku' &&
                    roleItem.id === commissionItem.roleId &&
                    commissionItem.goodsSkuId
                  ) {
                    ratioData.commissionPercents.push(
                      commissionItem.commissionPercent
                    )
                  }
                }
                this.distributionRatioData.push(ratioData)
              }
              this.levelArr = levelArr
              // 以下循环是把暂时没有配置分销比例的角色初始化到distributionRatioData中
              for (let roleItem in roleList) {
                for (let ratioData in this.distributionRatioData) {
                  if (roleItem.roleId === ratioData.roleId) {
                    continue
                  }
                  this.distributionRatioData.push({
                    roleId: roleItem.id,
                    roleTitle: roleItem.title,
                    roleDescription: roleItem.description,
                    commissionPercents: [
                      undefined,
                      undefined,
                      undefined,
                      undefined,
                      undefined,
                    ],
                  })
                }
              }
              this.distributionSpinShow = false
            })
            .catch((levelErr) => {
              console.log(levelErr)
            })
        })
        .catch((roleErr) => {
          console.log(roleErr)
        })
    },
    /**
     * 设置分销比例
     */
    setDistributionRatio() {
      const topDistributionRatioData = this.setTopDistributionRatioData()
      const distributionRatioData = this.setDistributionRatioData()
      const pickupDistributionRatioData = this.setPickupDistributionRatioData()
      if (
        this.topDistributionValidFlag &&
        this.pickupDistributionValidFlag &&
        this.distributionValidFlag
      ) {
        let ratioData = topDistributionRatioData
          .concat(distributionRatioData)
          .concat(pickupDistributionRatioData)
        if (ratioData.length <= 0) {
          this.$message.warning('没有需要保存的数据')
          return
        }
        this.setLoading = true
        utils
          .doPostJson(
            '/goods-commission/admin/remove-and-batch-save/' +
              this.type +
              '/' +
              this.id,
            topDistributionRatioData
              .concat(distributionRatioData)
              .concat(pickupDistributionRatioData),
            {}
          )
          .then((res) => {
            this.setLoading = false
            this.dialog = false
            this.$message.success('佣金比例配置分配成功')
          })
          .catch((err) => {
            console.log(err)
            this.setLoading = false
          })
      }
    },
    setPickupDistributionRatioData() {
      let listData = []
      const pickupDistributionRatioDataLen = this.pickupDistributionRatioData
        .length
      for (let i = 0; i < pickupDistributionRatioDataLen; i++) {
        let ratioData = this.pickupDistributionRatioData[i]
        const ratio = parseFloat(ratioData.commissionPercent)
        if (!ratio) {
          continue
        }
        if (ratio < 0) {
          this.$message.error('顶级返佣比例不能小于0')
          return
        }
        if (ratio > 100) {
          this.$message.error('顶级返佣比例不能大于100')
          return
        }
        listData.push({
          goodsId: this.goodsId,
          goodsTitle: this.goodsTitle,
          goodsPicUrl: this.goodsPicUrl,
          goodsIsActive: this.goodsIsActive,
          goodsSkuId: this.goodsSkuId,
          skuTitle: this.skuTitle,
          skuPicUrl: this.skuPicUrl,
          skuIsActive: this.skuIsActive,
          roleId: ratioData.roleId,
          roleTitle: ratioData.roleTitle,
          roleIsActive: 1,
          distributionLevel: -1,
          commissionPercent: ratio,
        })
      }
      this.pickupDistributionValidFlag = true
      return listData
    },
    setTopDistributionRatioData() {
      let listData = []
      const topDistributionRatioDataLen = this.topDistributionRatioData.length
      for (let i = 0; i < topDistributionRatioDataLen; i++) {
        let ratioData = this.topDistributionRatioData[i]
        const ratio = parseFloat(ratioData.commissionPercent)
        if (!ratio) {
          continue
        }
        if (ratio < 0) {
          this.$message.error('顶级返佣比例不能小于0')
          return
        }
        if (ratio > 100) {
          this.$message.error('顶级返佣比例不能大于100')
          return
        }
        listData.push({
          goodsId: this.goodsId,
          goodsTitle: this.goodsTitle,
          goodsPicUrl: this.goodsPicUrl,
          goodsIsActive: this.goodsIsActive,
          goodsSkuId: this.goodsSkuId,
          skuTitle: this.skuTitle,
          skuPicUrl: this.skuPicUrl,
          skuIsActive: this.skuIsActive,
          roleId: ratioData.roleId,
          roleTitle: ratioData.roleTitle,
          roleIsActive: 1,
          distributionLevel: 0,
          commissionPercent: ratio,
        })
      }
      this.topDistributionValidFlag = true
      return listData
    },
    setDistributionRatioData() {
      let listData = []
      const distributionRatioDataLen = this.distributionRatioData.length
      const levelLen = this.levelArr.length
      for (let i = 0; i < distributionRatioDataLen; i++) {
        let ratioData = this.distributionRatioData[i]
        for (let j = 0; j < levelLen; j++) {
          const ratio = parseFloat(ratioData.commissionPercents[j])
          if (!ratio) {
            continue
          }
          if (ratio < 0) {
            this.$message.error('分销返佣比例不能小于0')
            return
          }
          if (ratio > 100) {
            this.$message.error('分销返佣比例不能大于100')
            return
          }
          listData.push({
            goodsId: this.goodsId,
            goodsTitle: this.goodsTitle,
            goodsPicUrl: this.goodsPicUrl,
            goodsIsActive: this.goodsIsActive,
            goodsSkuId: this.goodsSkuId,
            skuTitle: this.skuTitle,
            skuPicUrl: this.skuPicUrl,
            skuIsActive: this.skuIsActive,
            roleId: ratioData.roleId,
            roleTitle: ratioData.roleTitle,
            roleIsActive: 1,
            distributionLevel: this.levelArr[j],
            commissionPercent: ratio,
          })
        }
      }
      this.distributionValidFlag = true
      return listData
    },
  },
  mounted() {},
}
</script>

<style lang="scss">
.zy-text-bold {
  font-weight: bold;
}
.zy-box {
  border: 1px solid #ccc;
  border-left: none;
  border-right: none;
  text-align: center;
  width: 100%;
  position: relative;
}

.zy-box-row {
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
.zy-box-row:last-child {
  border-bottom: none;
}
.zy-box-row div {
  float: left;
  width: 210px;
  padding: 0 20px 0 0;
  margin-right: 10px;
}
.zy-box-row div:last-child {
  border-right: 0;
}

.zy-input input {
  text-align: center;
  height: 20px;
  outline: 0;
  border: 0;
}
.zy-input input:focus {
  outline: 0;
  border: 0;
}
</style>
